﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Meraz.Core.Model;
using Meraz.Core.Repositories;

namespace Meraz.Core.Commands
{
    public interface IRemoveTwitterUserCommand : ICommand<bool>
    {
        string UserName { get; set; }
        int StudyID { get; set; }
        ITwitterUserRepository TwitterUserRepository { get; set; }
        ITwitterStudyRepository TwitterStudyRepository { get; set; }
    }
    public class RemoveTwitterUserCommand : BaseCommand, IRemoveTwitterUserCommand
    {
        public bool Result { get; set; }
        public string UserName { get; set; }
        public int StudyID { get; set; }
        public ITwitterUserRepository TwitterUserRepository { get; set; }
        public ITwitterStudyRepository TwitterStudyRepository { get; set; }
        public RemoveTwitterUserCommand(ITwitterUserRepository twitterUserRepository, ITwitterStudyRepository twitterStudyRepository)
        {
            TwitterUserRepository = twitterUserRepository ?? new TwitterUserRepository();
            TwitterStudyRepository = twitterStudyRepository ?? new TwitterStudyRepository();
        }

        public void Execute()
        {
            if (string.IsNullOrWhiteSpace(UserName))
                throw new ApplicationException("Missing username");
            TwitterUser user = TwitterUserRepository.GetByUsername(UserName);
            if (user == null)
                throw new ApplicationException("Invalid username");
            if (StudyID > 0)
            {
                TwitterStudy study = TwitterStudyRepository.GetById(StudyID);
                if (study == null)
                    throw new ApplicationException("Invalid study ID");

                study.TwitterUsers.Remove(user);
            }
            else
            {
                List<TwitterStudy> studies = TwitterStudyRepository.GetByUserName(UserName);
                if (studies.Count > 0)
                    return;

                TwitterUserRepository.Delete(user);
            }
            Commit();
            this.Result = true;
        }
    }
}
